'use strict';

const Controller = require('egg').Controller;
class UserController extends Controller {
  async show() {
    const { response: res, app } = this.ctx;
    console.log(app);
    res.body = app.userInfo;
  }

  async create() {
    const ctx = this.ctx;
    const { name, age } = ctx.request.body;
    const user = await ctx.model.User.create({ name, age });
    ctx.status = 201;
    ctx.body = user;
  }

  async update() {
    // 修改密码
    const { response: res, request: req, app, logger } = this.ctx;
    const { old, neo, confirm } = req.body;
    if (!app.userInfo.active && old === '') {
      logger.info(1);
      res.body = {
        code: 401,
      };
      return;
    }
    if (neo === '' || confirm === '' || neo !== confirm) {
      logger.info(2, neo, confirm);
      res.body = {
        code: 401,
      };
      return;
    }

    const user = await app.model.User.findByPk(app.userInfo.id);
    await user.update(
      { password: neo, active: 1 },
      {
        where: {
          id: app.userInfo.id,
        },
      }
    );
    res.body = {
      active: 1,
    };
  }

  async destroy() {
    // const ctx = this.ctx;
    // const id = toInt(ctx.params.id);
    // const user = await ctx.model.User.findByPk(id);
    // if (!user) {
    //   ctx.status = 404;
    //   return;
    // }
    // await user.destroy();
  }
}

module.exports = UserController;
